<?

class cli
{
	public static function run( $params )
	{
		cache::disable_local_cache();
		db_mysql::disable_local_cache();
		
		array_shift($params);
		$task = array_shift($params);

		if ( $task ) self::run_task($task, $params);
		else self::show_help();
	}

	public static function run_task( $name, $params )
	{
		$t = microtime(true);
		$name = str_replace(':', '_', $name) . '_task';
		
		if ( !class_exists($name) )
			return print "Error: unknown task {$name}\n";

		$task = new $name( new cli_output );
		if ( !$task->silent_mode ) echo "Running {$name}\n\n";
		$task->execute( $params );

		if ( !$task->silent_mode )
		{
			echo "\n";
			echo "Finished in " . round( microtime(true) - $t, 4 ) . 's, ';
			echo round( memory_get_usage()/(1024*1024), 3 ) . "mb consumed \n\n";
		}
	}

	public static function show_help()
	{
		echo "\nAvailable tasks:\n";

		self::print_tasks( dirname(__FILE__) . '/../tasks' );
		if ( defined('PROJECT_PATH') && is_dir(PROJECT_PATH . '/lib/tasks') ) self::print_tasks(PROJECT_PATH . '/lib/tasks');

		echo "\n";
	}

	public static function print_tasks( $dir )
	{
		$i = new RecursiveIteratorIterator(
				new RecursiveDirectoryIterator($dir),
				RecursiveIteratorIterator::SELF_FIRST
			);

		foreach ( $i as $file )
		{
			if ( pathinfo($file, PATHINFO_EXTENSION) == 'php' )
			{
				$task = str_replace(array($dir . '/', '/', '.php'), array('', '_', ''), $file);
				if ( $task == 'system_task' ) continue;
				
				echo ' - ' . $task . "\n";
			}
		}
	}
}

class cli_output
{
	public function out( $message )
	{
		echo $message . "\n";
	}
}